/*
 *  Copyright 2020-2025 the original author or authors.
 *  You cannot use this file unless authorized by the author.
 */

package org.ipig.commons.helper;

import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * FileHelper
 *
 * @author <a href="mailto:comchnts@163.com">chinats</a>
 * @version $$Id$$
 * @since 1.0
 */
public class FileHelper {
    /**
     * 读取文本文件中的所有非空行
     *
     * @param file     文件
     * @param encoding 编码
     * @return List<String>
     * @throws IOException IOException
     */
    public static List<String> readLinesTrimEmptyLine(File file, String encoding) throws IOException {
        return readLinesTrimEmptyLine(file, encoding, true);
    }

    /**
     * 读取文本文件中的所有行
     *
     * @param file              文件
     * @param encoding          编码
     * @param trimEmptyLineFlag 去除空行标志 true：去除空行 false 不处理
     * @return List<String>
     * @throws IOException IOException
     */
    public static List<String> readLinesTrimEmptyLine(File file, String encoding, Boolean trimEmptyLineFlag) throws IOException {
        InputStream in = null;
        try {
            in = org.apache.commons.io.FileUtils.openInputStream(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charsets.toCharset(encoding)));
            List<String> list = new ArrayList<String>();
            String line = reader.readLine();
            while (line != null) {
                if (trimEmptyLineFlag) {
                    if (StringUtils.isNotBlank(line)) {
                        list.add(line);
                    }
                } else {
                    list.add(line);
                }
                line = reader.readLine();
            }
            return list;
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
}
